/*****************************************************
* FILE : random_out.c
* NAME : Joe Armstrong
* COURSE : CS 454 Fall 2009
****************************************************** 
* Explanation : 
* This program uses the /dev/dsp sound device to take
* an input. It then adds up the buffer, uses it as a seed
* and then outputs the random number to a file for testing.
* It also prints out the numbers so you can look at them
******************************************************/

#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <stdio.h>
#include <linux/soundcard.h>

#define LENGTH 1    	// RECORD FOR 1 SECOND
#define RATE 8000   	// SAMPLE RATE
#define SIZE 8      	// SAMPLE AT 8bits
#define CHANNELS 1  	// RECORD IN MONO
#define RANGEMIN 1		//Minimum value in range
#define RANGEMAX 1000	//Minimum value in range

unsigned char buf[LENGTH*RATE*SIZE*CHANNELS/8]; //buffer to hold the data

int main()
{

  int fd;	// sound device file descriptor
  int arg;	// value ioctl calls
  int status;   // return value for system calls


  //open the /dev/dsp sound device
  fd = open("/dev/dsp", O_RDWR);
  if (fd < 0) {
    perror("ERROR : FAILED TO OPEN DEVICE");
    exit(1);
  }

  arg = SIZE;	   //set the sample size
  status = ioctl(fd, SOUND_PCM_WRITE_BITS, &arg);
  arg = CHANNELS;  //set the channels
  status = ioctl(fd, SOUND_PCM_WRITE_CHANNELS, &arg);

  arg = RATE;	   // set the rate
  status = ioctl(fd, SOUND_PCM_WRITE_RATE, &arg);

//SOME FILES
  FILE *file;
  file = fopen("../Data_Sets/file-true.bin","a+");

  FILE *file2;
  file2 = fopen("../Data_Sets/file-rand.bin","a+");

  FILE *file3;
  file3 = fopen("../Data_Sets/file-srandSeed.bin","a+");

//Variables need for while loop
  int i;
  int random;
  int randInt;

/*
This is the main loop that records input for 1 second, adds up the buffer into an
integer, uses that as a seed, outputs the random number as binary to a file for testing.
*/
while(1){

   read(fd, buf, sizeof(buf)); //read sound from f
    //counts for loop and random number

   random = 0;
   for(i=0;i<sizeof(buf);i++)
	random = random + buf[i];

    fprintf(file,"%d\n",random);
    printf("RANDOM INT FROM BUFFER : %d\n",random);

    //define range
    randInt = RANGEMIN + (rand () % (RANGEMIN+(RANGEMIN-RANGEMAX)));

    fprintf(file2,"%d\n",randInt);
    printf("PSUEDO-RANDOM INT FROM RAND() : %d\n",randInt);

    srand(random);

    //define range
    randInt = RANGEMIN + (rand () % (RANGEMIN+(RANGEMIN-RANGEMAX)));

    printf("PSUEDO-RANDOm INT WITH SRAND() RANDOM SEED : %d\n",randInt);
    fprintf(file3,"%d\n",randInt);

    //Flush to files
    fflush(file);
    fflush(file2);
    fflush(file3);

}//END LOOP

    //close the files
    fclose(file);
    fclose(file2);
    fclose(file3);

}//END MAIN
